package com.itheima.appserver.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.config.MyCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 对查询数据拦截，并从redis中查询数据
 *
 * @Author: lqTao
 * @Date: 2021/12/9 15:59
 */
@Component
public class CacheInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    //请求目标资源之前，增强
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        if (!((HandlerMethod) handler).hasMethodAnnotation(MyCache.class)) {
            return true;
        }
        if (!((HandlerMethod) handler).hasMethodAnnotation(GetMapping.class)) {
            return true;
        }
        String value = redisTemplate.opsForValue().get(cacheKey(request));

        if (ObjectUtil.isNull(value)) {
            //redis中还没有数据
            return true;
        }

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(value);
        System.out.println("数据从缓存中取走了");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    public static String cacheKey(HttpServletRequest request) {
        //需要通过2个参数确定该请求唯一
        //1、请求路径
        //2、请求参数
        String requestURI = request.getRequestURI();
        Map<String, String[]> parameterMap = request.getParameterMap();
        String token = request.getParameter("Authorization");

        return SecureUtil.md5(requestURI + "_" + JSONUtil.toJsonStr(parameterMap) + "_" + token);
    }

}
